//
//  UITextView+Extension.swift
//  表情键盘
//
//  Created by 梁智 on 15/12/3.
//  Copyright © 2015年 lzfree. All rights reserved.
//

import UIKit

extension UITextView {
    
    /// 返回 textView 的完整表情字符串
    var emoticonText: String {
        
        let attrText = attributedText
        var strM = String()
        
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, range, _) -> Void in
            
            // 根据输出判定如果字典中包含 NSAttachment 是图片，否则是文本
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                strM += attachment.emoticon.chs ?? ""
            } else {
                let str = (attrText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
    
    /// 插入表情符号
    ///
    /// - parameter em: 表情模型
    func insertEmoticon(em: Emoticon) {
        print(em)
        
        // 空白表情
        if em.isEmpty {
            return
        }
        
        // 删除按钮
        if em.isRemoved {
            deleteBackward()
            return
        }
        
        // emoji
        if let emoji = em.emoji {
            replaceRange(selectedTextRange!, withText: emoji)
            
            return
        }
        
        // 图片表情
        insertImageEmoticon(em)
        
        // 调用代理方法
        delegate?.textViewDidChange?(self)
    }
    
    /// 插入图片表情
    private func insertImageEmoticon(em: Emoticon) {
        
        let imageText = EmoticonAttachment(emoticon: em).imageText(font!)
        
        // 2. 记录 textView attributeString －> 转换成可变文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        // 替换属性文本内容
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        // 3. 重新更新 textView 中的属性文本
        // 记录光标位置
        let range = selectedRange
        // 替换文本
        attributedText = strM
        // 恢复光标
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
}